import 'dart:io';
import 'dart:typed_data';
import 'package:path_provider/path_provider.dart';

class utilFile {
  /// 获取应用文档目录路径
  static Future<String> getAppDocPath() async {
    final dir = await getApplicationDocumentsDirectory();
    return dir.path;
  }

  /// 创建文件夹
  static Future<Directory> createFolder(String folderName) async {
    final path = await getAppDocPath();
    final dir = Directory('$path/$folderName');
    if (!(await dir.exists())) {
      await dir.create(recursive: true);
    }
    return dir;
  }

  /// 删除文件夹（包含内容）
  static Future<void> deleteFolder(String folderName) async {
    final path = await getAppDocPath();
    final dir = Directory('$path/$folderName');
    if (await dir.exists()) {
      await dir.delete(recursive: true);
    }
  }

  /// 创建文件（可自动创建父目录）
  static Future<File> createFile(String fileName, {String folder = ""}) async {
    final basePath = await getAppDocPath();
    final fullPath = folder.isNotEmpty ? "$basePath/$folder/$fileName" : "$basePath/$fileName";
    final file = File(fullPath);
    if (!(await file.exists())) {
      await file.create(recursive: true);
    }
    return file;
  }

  /// 删除文件
  static Future<void> deleteFile(String fileName, {String folder = ""}) async {
    final basePath = await getAppDocPath();
    final fullPath = folder.isNotEmpty ? "$basePath/$folder/$fileName" : "$basePath/$fileName";
    final file = File(fullPath);
    if (await file.exists()) {
      await file.delete();
    }
  }

  /// 写入字符串内容到文件（覆盖写入）
  static Future<void> writeFile(String fileName, String content, {String folder = ""}) async {
    final file = await createFile(fileName, folder: folder);
    await file.writeAsString(content);
  }

  /// 读取文件内容为字符串
  static Future<String> readFile(String fileName, {String folder = ""}) async {
    final basePath = await getAppDocPath();
    final fullPath = folder.isNotEmpty ? "$basePath/$folder/$fileName" : "$basePath/$fileName";
    final file = File(fullPath);
    return await file.exists() ? await file.readAsString() : "";
  }

  /// 保存图片（Uint8List）到本地
  static Future<void> saveImageFile(String fileName, Uint8List bytes, {String folder = ""}) async {
    final file = await createFile(fileName, folder: folder);
    await file.writeAsBytes(bytes);
  }

  /// 读取本地图片为 Uint8List
  static Future<Uint8List?> readImageFile(String fileName, {String folder = ""}) async {
    final basePath = await getAppDocPath();
    final fullPath = folder.isNotEmpty ? "$basePath/$folder/$fileName" : "$basePath/$fileName";
    final file = File(fullPath);
    return await file.exists() ? await file.readAsBytes() : null;
  }

  /// 判断文件是否存在
  static Future<bool> fileExists(String fileName, {String folder = ""}) async {
    final basePath = await getAppDocPath();
    final fullPath = folder.isNotEmpty ? "$basePath/$folder/$fileName" : "$basePath/$fileName";
    return File(fullPath).exists();
  }
}